
package com.jsjosem.aftersales.ui.mine;

import static com.jsjosem.aftersales.constant.CommonConstant.LOGIN_USER;
import static com.jsjosem.aftersales.constant.CommonConstant.USER_INFO;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.jsjosem.aftersales.R;
import com.jsjosem.aftersales.api.RetrofitClient;
import com.jsjosem.aftersales.api.UserApi;
import com.jsjosem.aftersales.cache.UserCache;
import com.jsjosem.aftersales.component.ConfirmDialog;
import com.jsjosem.aftersales.data.response.BaseResponse;
import com.jsjosem.aftersales.data.response.LoggedInUser;
import com.jsjosem.aftersales.data.response.LoginUserResponse;
import com.jsjosem.aftersales.databinding.FragmentMineBinding;
import com.jsjosem.aftersales.request.AsyncRequest;
import com.jsjosem.aftersales.ui.login.LoginActivity;
import com.wang.avi.AVLoadingIndicatorView;

import retrofit2.Call;
import retrofit2.Retrofit;

public class MineFragment extends Fragment {

    private FragmentMineBinding binding;
    private ScrollView view;
    private TextView tvCompany;
    private TextView tvUsername;
    private TextView tvMobile;
    private ImageView ivHeadPicture;
    private UserCache userCache;
    private LoggedInUser loggedInUser;
    private Retrofit retrofit;
    private UserApi userApi;
    private SharedPreferences sp;
    private Context context;
    private Dialog loadingDialog;
    private ConstraintLayout clLogout;
    private SharedPreferences.Editor edit;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentMineBinding.inflate(inflater, container, false);
        view = binding.getRoot();
        context = view.getContext();
        initView();
        initData();
        logout();
        return view;
    }

    private void logout() {
        clLogout.setOnClickListener(v -> {
            ConfirmDialog confirmDialog = new ConfirmDialog(context, () -> {
                // 退出登录，清空用户信息。
                edit.clear();
                edit.commit();
                userCache.clear();
                // 跳转到登录页
                Intent intent = new Intent(context, LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            });
            confirmDialog.setTitle("提示");
            confirmDialog.setContent("确定要退出登录吗？");
        });
    }

    private void initData() {
        loadingShow();
        retrofit = RetrofitClient.getInstance();
        userApi = retrofit.create(UserApi.class);
        userCache = UserCache.getInstance();
        loggedInUser = UserCache.getInstance().getUser();
        tvUsername.setText(loggedInUser.getName());
        tvCompany.setText(loggedInUser.getDepartment());
        tvMobile.setText(loggedInUser.getTelephone());
        Glide.with(this)
                .load(loggedInUser.getAvatar())
                .placeholder(R.drawable.rotate_pro)
                .error(R.drawable.load_failed_24dp)
                .override(100, 100)
                .into(ivHeadPicture);
        getUser();
    }

    private void getUser() {
        // 获取当前登录用户信息
        Call<BaseResponse<LoginUserResponse>> loginUserInfo = userApi.getLoginUserInfo();
        AsyncRequest<BaseResponse<LoginUserResponse>> getLoginUserReq = new AsyncRequest<>();
        getLoginUserReq.sendRequest(loginUserInfo, (userRes) -> {
            LoginUserResponse data = userRes.getData();
            loggedInUser.setEmail(data.getmEmail());
            loggedInUser.setExpired_at(data.getmExpiredTime());
            loggedInUser.setId(data.getmId());
            loggedInUser.setName(data.getmRealname());
            loggedInUser.setTelephone(data.getmMobile());
            loggedInUser.setAvatar(data.getmAvatar());
            loggedInUser.setDepartment(data.getmDeptName());
            loggedInUser.setDepartmentId(data.getmDeptId());
            userCache.setUser(loggedInUser);
            // 保存用户的账户信息
            sp = context.getSharedPreferences(USER_INFO, Context.MODE_PRIVATE);
            edit = sp.edit();
            edit.putString(LOGIN_USER, new Gson().toJson(userCache));
            edit.apply();
            loadingDialog.dismiss();
        }, failedMessage -> {
            loadingDialog.dismiss();
            Toast.makeText(context, failedMessage.toString(), Toast.LENGTH_SHORT).show();
        });
    }

    private void initView() {
        tvUsername = view.findViewById(R.id.user_name_tv);
        tvCompany = view.findViewById(R.id.user_company_tv);
        tvMobile = view.findViewById(R.id.user_mobile_tv);
        ivHeadPicture = view.findViewById(R.id.headpicture_iv);
        clLogout = view.findViewById(R.id.cl_logout);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    public void loadingShow() {
        loadingDialog = new Dialog(context, R.style.normal_dialog_style);
        View loadingView = View.inflate(context, R.layout.dialog_loading, null);
        loadingDialog.setContentView(loadingView);
        //使得点击对话框外部不消失对话框
        loadingDialog.setCanceledOnTouchOutside(false);
        AVLoadingIndicatorView avi = loadingView.findViewById(R.id.avi);
        avi.show();
        loadingDialog.show();
    }
}